import Taro from '@tarojs/taro'
import {setGlobalData} from "../../global.d";
import {getUser} from "../class/service";
import {toast} from "../../utils";

const db = Taro.cloud.database();

// 授权登录
export async function authLogin(userInfo, redirect) {
  if (!userInfo) {
    userInfo = await Taro.getUserInfo().then(res => {
      return res.userInfo;
    }).catch(err => {
      toast('请授权登录');
      console.log(err);
    });
  }
  if (userInfo) {
    let user = await getUser();
    user.userInfo = userInfo;
    updateUserInfo(user._id, userInfo);
    setGlobalData('user', user);
    console.log(`userId: ${user._id} 登录成功`);
    if (redirect) {
      // 重定向至主页
      Taro.redirectTo({
        url: '/pages/guide/index'
      })
    }
    return user;
  }
}

// 更新数据库中用户的userInfo
export function updateUserInfo(userId, userInfo) {
  // 插入用户
  db.collection('user')
    .doc(userId)
    .update({
      data: {
        userInfo
      }
    })
    .then(res => {
      console.log(res);
    }).catch(err => {
    console.error(`更新用户信息失败，err: ${err}`);
  })
}
